// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid =  wxContext.OPENID
  let resInfo = ''
  await db.collection('user').where({
    username: event.username,
    password: event.password
  }).get().then(async res=>{
    if(res.data.length != 0){
      await db.collection('user').doc(res.data[0]._id).update({
        data: {
          loginDate: openid + Date.now()
        }
      }).then(a=>{
        resInfo = a
      })
    }else {
      await db.collection('user').add({
        data: {
          username: event.username,
          password: event.password,
          loginDate: openid + Date.now(),
          openId: openid
        }
      }).then(b=>{
        resInfo = b
      })
    }
  })
  return resInfo
}